import React, { useEffect, useState } from 'react'
import {
  Button,
  Form,
  Input,
  Modal,
  Table,
  InputNumber,
  Select,
  DatePicker,
} from 'antd'
import './user.css'
import { getUserList, addUserApi, editUserApi, deleteUserApi } from '../../api'
import dayjs from 'dayjs'

const User = () => {
  const [searchData, setSearchData] = useState({
    name: '',
  })
  const [tableData, setTableData] = useState([])
  const [modalType, setModalType] = useState('add')
  const [isShowModal, setIsShowModal] = useState(false)

  const [formData] = Form.useForm()

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render: (row) => {
        return row ? '女' : '男'
      },
    },
    {
      title: '出身日期',
      dataIndex: 'birth',
    },
    {
      title: '地址',
      dataIndex: 'addr',
    },
    {
      title: '操作',
      width: '180px',
      render: (rowData) => {
        return (
          <div className="flex-box">
            <Button onClick={() => handleAddEdit('edit', rowData)}>编辑</Button>
            <Button danger onClick={() => handleDelete(rowData)}>
              删除
            </Button>
          </div>
        )
      },
    },
  ]

  /** 提交 */
  const handleFinish = (val) => {
    setSearchData({
      name: val.keyword,
    })
  }

  /** 删除 */
  const handleDelete = async (rowData) => {
    try {
      await deleteUserApi(rowData)
      getUserListFn()
    } catch (error) {
      console.error(error)
    }
  }

  /** 新增编辑 */
  const handleAddEdit = (type, rowData) => {
    setModalType(type)
    setIsShowModal(!isShowModal)
    if (rowData) {
      const cloneData = JSON.parse(JSON.stringify(rowData))
      cloneData.birth = dayjs(cloneData.birth)
      formData.setFieldsValue(cloneData)
    }
  }

  /** 取消弹框 */
  const handleCancel = () => {
    setIsShowModal(false)
    formData.resetFields()
  }

  /** 确认弹框 */
  const handleOk = () => {
    formData
      .validateFields()
      .then((val) => {
        val.birth = dayjs(val.birth).format('YYYY-MM-DD')
        handleAddEditRequest(val)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  /** 新增编辑 */
  const handleAddEditRequest = async (params) => {
    try {
      if (modalType === 'add') {
        await addUserApi(params)
      } else {
        await editUserApi(params)
      }
      handleCancel()
      getUserListFn()
    } catch (error) {
      console.error(error)
    }
  }

  /** 获取表格数据 */
  const getUserListFn = async () => {
    const { data: { list } } = await getUserList(searchData)
    setTableData(list)
  }

  useEffect(() => {
    getUserListFn()
  }, [searchData])

  return (
    <div className="user-container">
      <div className="flex-box">
        <Button type="primary" icon="+" onClick={() => handleAddEdit('add')}>
          新增
        </Button>
        <Form layout="inline" onFinish={handleFinish}>
          <Form.Item name="keyword">
            <Input />
          </Form.Item>
          <Form.Item>
            <Button htmlType="submit" type="primary">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>

      <Table
        style={{ marginTop: '20px' }}
        columns={columns}
        dataSource={tableData}
        rowKey="id"
      />

      <Modal
        open={isShowModal}
        title={modalType === 'add' ? '新增' : '编辑'}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={formData}
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 18,
          }}
          labelAlign="left"
        >
          {modalType === 'edit' && <Form.Item name="id" hidden />}
          <Form.Item
            label="姓名"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入姓名',
              },
            ]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            label="年龄"
            name="age"
            rules={[
              {
                required: true,
                message: '请输入年龄',
              },
              {
                type: 'number',
                message: '年龄必须是数字',
              },
            ]}
          >
            <InputNumber placeholder="请输入年龄" />
          </Form.Item>
          <Form.Item
            label="性别"
            name="sex"
            rules={[
              {
                required: true,
                message: '请选择性别',
              },
            ]}
          >
            <Select
              options={[
                {
                  label: '男',
                  value: 0,
                },
                {
                  label: '女',
                  value: 1,
                },
              ]}
              placeholder="请选择性别"
            />
          </Form.Item>
          <Form.Item
            label="出身日期"
            name="birth"
            rules={[
              {
                required: true,
                message: '请选择出身日期',
              },
            ]}
          >
            <DatePicker format="YYYY/MM/DD" placeholder="请选择" />
          </Form.Item>
          <Form.Item
            label="地址"
            name="addr"
            rules={[
              {
                required: true,
                message: '请填写地址',
              },
            ]}
          >
            <Input placeholder="请填写地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default User
